﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using MaterialDesignExtensions.Controls;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using System.Windows.Controls;
using Masuit.Tools.Models;
using EntranceGuardManager.Modules.Main.Views;
using Microsoft.EntityFrameworkCore;
using AJWPFAdmin.Core.Models.EF.Tables;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using AJWPFAdmin.Modules.Common.Views;
using AJWPFAdmin.Services.AppointAPI;
using AJWPFAdmin.Core;
using DocumentFormat.OpenXml.Wordprocessing;

namespace EntranceGuardManager.Modules.Main.ViewModels
{

    public class IllegalVehicleListViewModel : BindableBase, INavigationAware
    {

        private AJTableFetchOptions _fetchOptions;

        public AJTableFetchOptions FetchOptions
        {
            get
            {
                return _fetchOptions;
            }
            set
            {
                SetProperty(ref _fetchOptions, value);
            }
        }

        private List<AJTableColumnItem> _columns;

        public List<AJTableColumnItem> Columns
        {
            get { return _columns; }
            set { SetProperty(ref _columns, value); }
        }

        private AJTableSearchFormConfig _formConfig;

        public AJTableSearchFormConfig FormConfig
        {
            get { return _formConfig; }
            set { SetProperty(ref _formConfig, value); }
        }

        private DelegateCommand<DataGridRow> _loadingRowCmd;
        public DelegateCommand<DataGridRow> LoadingRowCmd =>
            _loadingRowCmd ?? (_loadingRowCmd = new DelegateCommand<DataGridRow>(ExecuteLoadingRowCmd));

        void ExecuteLoadingRowCmd(DataGridRow row)
        {

        }

        private DelegateCommand<IllegalVehicleRecord> _openUploadCheckCmd;
        public DelegateCommand<IllegalVehicleRecord> OpenUploadCheckCmd =>
            _openUploadCheckCmd ?? (_openUploadCheckCmd = new DelegateCommand<IllegalVehicleRecord>(ExecuteOpenUploadCheckCmd));

        void ExecuteOpenUploadCheckCmd(IllegalVehicleRecord parameter)
        {
            var @params = new DialogParameters
            {
                { "data", parameter },
                //{ "typeOptions", _typeOptions },
            };
            _dialogSvc.ShowDialog(nameof(IllegalVehicleUploadCheckForm), @params, r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    FetchOptions.RequestRefresh(false);
                }
            });
        }

        private IDialogService _dialogSvc;
        private DbService db;
        private AppointAPISvc _appointAPISvc;
        private SystemConfigKey _apiKey;

        public IllegalVehicleListViewModel(DbService dbIns, AppointAPISvc appointAPISvc, IEventAggregator eventAggregator, IDialogService dialogSvc)
        {

            _dialogSvc = dialogSvc;
            _appointAPISvc = appointAPISvc;
            _apiKey = _appointAPISvc.API.Config.Key;
            //eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() => Loading = false);

            FetchOptions = new AJTableFetchOptions
            {
                //ExportFileName = "车辆记录导出",
                Handle = async (formCfg, pageCfg) =>
                {
                    var carNo = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(IllegalVehicleRecord.CarNo)).Value?.ToString();

                    var color = FormConfig.Schemas
                .FirstOrDefault(p => p.Field == nameof(IllegalVehicleRecord.Color)).Value as CarPlateColor?;

                    //if ((!string.IsNullOrWhiteSpace(@params.CarNo) && @params.Color == null)
                    //|| (string.IsNullOrWhiteSpace(@params.CarNo) && @params.Color.HasValue))
                    //{
                    //    ExceptionTool.FriendlyError("车牌号和号牌颜色必须同时搜索");
                    //}

                    var dates = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(IllegalVehicleRecord.EntryTime))?.Value as ObservableCollection<DateTime?>;

                    var start = dates?.ElementAtOrDefault(0);
                    var end = dates?.ElementAtOrDefault(1);

                    //if (start.HasValue && end.HasValue)
                    //{
                    //    if (start.GetValueOrDefault().Subtract(end.GetValueOrDefault()).TotalDays > 90)
                    //    {
                    //        ExceptionTool.FriendlyError("时间跨度不能超过90天");
                    //    }
                    //}

                    var list = await db.IllegalVehicleRecords
                    .IfWhere(() => start.HasValue && start != DateTime.MinValue, p => p.EntryTime >= start)
                    .IfWhere(() => end.HasValue && end != DateTime.MinValue, p => p.EntryTime <= end)
                    .LikeOrLike(carNo, p => p.CarNo)
                    .Where(p => p.API == _apiKey)
                    .ToPagedListAsync(pageCfg.Current, pageCfg.PageSize);

                    return new AJTableFetchResult
                    {
                        Total = list.TotalCount,
                        HasNext = list.HasNext,
                        Rows = list.Data
                    };
                }
            };

            var end = DateTime.Today;
            var start = end.AddDays(90).Date;

            var dateRangeSchema = new AJTableSearchFormSchema
            {
                Labels = new string[] { "进场开始日期", "进场结束日期" },
                Field = nameof(IllegalVehicleRecord.EntryTime),
                Type = AJTableSchemaType.RangePicker,
                Value = new ObservableCollection<DateTime?>(new DateTime?[2] { start, end }),
                IsPopular = true,
            };

            FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {
                    new AJTableSearchFormSchema
                    {
                        Label = "车牌号",
                        Field = nameof(IllegalVehicleRecord.CarNo),
                        Type = AJTableSchemaType.Input,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "号牌颜色",
                        Field = nameof(IllegalVehicleRecord.Color),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                        Options = new ObservableCollection<AJTableFormSchemaItemOptions>(CommonUtil.EnumToDictionary<CarPlateColor>(null).Select(p => new AJTableFormSchemaItemOptions
                        {
                            Label = p.Key,
                            Value = p.Value
                        }))
                    },
                    dateRangeSchema
                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };

            var columns = new List<AJTableColumnItem> {
                new AJTableColumnItem
                {
                    Title = "操作",
                    CustomTemplate = new AJTableCustomTemplate
                    {
                        Key = "TableOperatioin"
                    },
                    Fixed = AJTableColumnFixedType.Right,
                    Width = new DataGridLength(160),
                },
            };

            var props = typeof(IllegalVehicleRecord).GetRuntimeProperties();

            foreach (var prop in props)
            {
                var attr = prop.GetCustomAttribute<DisplayAttribute>();
                if (attr == null
                    || prop.Name.Equals(nameof(IllegalVehicleRecord.API)))
                {
                    continue;
                }
                var col = new AJTableColumnItem
                {
                    DataIndex = prop.Name,
                    Title = attr.Name
                };
                if(prop.Name == nameof(IllegalVehicleRecord.CheckResult))
                {
                    col.Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return val == null ? "--" : (int)val == 0 ? "超标" : "不超标";
                        }
                    };
                }
                columns.Add(col);
            }

            Columns = columns;

            db = dbIns;
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            await Task.Delay(2000);

            FetchOptions.RequestRefresh(false);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
    }
}
